package ua.kiev.tosik.price.modules.clients.database;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IClientsDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Clients;
import ua.kiev.tosik.price.modules.clients.gui.MainPanel;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class DataQuickFindWorker extends SwingWorker<List<Clients>, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database");
	private List<Clients> clientsList;
	private IClientsDao clientsDao;
	private Clients client;

	public DataQuickFindWorker(Clients client) {
		super();
		logger.debug("Initialize DataQuickFindWorker");
		this.client = client;
		clientsList = new ArrayList<Clients>();
		try {
			clientsDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createClientsDao();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	@Override
	protected List<Clients> doInBackground() throws Exception {
		if ( clientsDao != null ) {
			firePropertyChange("SEARCH_START", false, AppConfig.getInstance().get("clients.data.loading"));
			clientsList = clientsDao.findByName(client.getName());
		}
		firePropertyChange("SEARCH_DONE", false, true);
		logger.debug("Found " + clientsList.size() + " records");
		return clientsList;
	}

	@Override
	protected void done() {
		try {
			clientsList = get();
			firePropertyChange("ClientsList", null, clientsList);
			MainPanel.getInstance().getTable().getModel().addRowSet(clientsList);
			MainPanel.getInstance().getToolBar().setRecordFoundInfoText("Found " + clientsList.size() + " record(s)");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
